package co.fitstart.weapp.api.web.controller.course;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.DateFormatUtils;

import co.fitstart.entity.course.CourseType;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.courseware.CoursewareTag;
import co.fitstart.entity.courseware.fitnessgroup.BatchCourseware;
import co.fitstart.entity.courseware.fitnessgroup.Courseware;
import co.fitstart.entity.courseware.fitnessgroup.CoursewareMovementType;
import co.fitstart.entity.courseware.fitnessgroup.DailyCourseware;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CoursewareService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/profile/courses/{courseId}")
public class CoursewareController {

    private static final Logger logger = LoggerFactory.getLogger(CoursewareController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CoursewareService coursewareService;
    
    

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/weekly-plans", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult listWeeklyPlan(@RequestParam("unionid") String unionid,
                                      @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            List<BatchCourseware> batchCoursewares = coursewareService.generallyListWeeklyPlan(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("batchCoursewares", batchCoursewares);
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("listWeeklyPlan() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/weekly-plans/{batchId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult weeklyPlan(@RequestParam("unionid") String unionid,
                                 @PathVariable("courseId") Long courseRoundId,
                                 @PathVariable("batchId") Long batchId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            if(student == null || batchCourseware == null || batchCourseware.getCourseRound().getStudent() != student) {
                httpResult.fail("1").message("课程异常");
            } else {
                CourseType courseType = batchCourseware.getCourseRound().getCourseType();
                httpResult.success().message("获取数据成功")
                                    .data("courseType", courseType)
                                    .data("name", batchCourseware.getName());
                
                if(courseType.isOnline()) {
                    httpResult.data("showTags", !batchCourseware.getCourseRound().getStudent().getArrayTagIds().isEmpty())
                              .data("showCoachTips", StringUtils.isNotBlank(batchCourseware.getCoachTips()))
                              .data("dailyCoursewares", batchCourseware.getDailyCoursewares());
                } else {
                    httpResult.data("dietary", coursewareService.generallyLoadDietary(batchCourseware))
                              .data("exercise", coursewareService.loadExercise(batchCourseware));
                    
                    if(batchCourseware.getBegin() != null && batchCourseware.getEnd() != null) {
                        httpResult.data("week", DateFormatUtils.format(batchCourseware.getBegin(), "yyyy-MM-dd") + "至" + DateFormatUtils.format(batchCourseware.getEnd(), "yyyy-MM-dd"));
                    } else if(batchCourseware.getCourseRound().getEffectiveStart() != null) {
                        Map<String, Date> map = coursewareService.getWeekBeginAndEnd(batchCourseware.getCourseRound(), batchCourseware.getSorting());
                      
                        httpResult.data("week", DateFormatUtils.format(map.get("begin"), "yyyy-MM-dd") + "至" + DateFormatUtils.format(map.get("end"), "yyyy-MM-dd"));
                    }
                }
            }
        } catch (Exception e) {
            logger.error("weeklyPlan() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/weekly-plans/{batchId}/dietary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult dietary(@RequestParam("unionid") String unionid,
                              @PathVariable("courseId") Long courseRoundId,
                              @PathVariable("batchId") Long batchId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            if(student == null || batchCourseware == null || batchCourseware.getCourseRound().getStudent() != student) {
                httpResult.fail("1").message("课程异常");
            } else {
                httpResult.success().data("dietarys", coursewareService.listDietary(batchCourseware))
                                    .data("title", batchCourseware.getName() + "饮食");
            }
        } catch (Exception e) {
            logger.error("dietary() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/student-tags", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult studentTags(@RequestParam("unionid") String unionid,
                                  @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            
            httpResult.success().data("tags", coursewareService.listCoursewareTags(student.getArrayTagIds()));
        } catch (Exception e) {
            logger.error("studentTags() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/weekly-plans/{batchId}/coach-tips", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult coachTips(@RequestParam("unionid") String unionid,
                                @PathVariable("courseId") Long courseRoundId,
                                @PathVariable("batchId") Long batchId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            if(student == null || batchCourseware == null || batchCourseware.getCourseRound().getStudent() != student) {
                httpResult.fail("1").message("课程异常");
            } else {
                httpResult.success().data("coachTips", batchCourseware.getCoachTips());
            }
        } catch (Exception e) {
            logger.error("coachTips() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @param dailyId
     * @return
     */
    
    
    @RequestMapping(value = "/weekly-plans/{batchId}/daily-coursewares/{dailyId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult dailyCourseware(@RequestParam("unionid") String unionid,
                                      @PathVariable("courseId") Long courseRoundId,
                                      @PathVariable("batchId") Long batchId,
                                      @PathVariable("dailyId") Long dailyId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            DailyCourseware dailyCourseware = coursewareService.loadDailyCourseware(dailyId);
            
            if(student == null || dailyCourseware == null || dailyCourseware.getBatch().getCourseRound().getStudent() != student) {
                httpResult.fail("1").message("课程异常");
            } else {
                httpResult.success().message("获取数据成功")
                                    .data("daily", dailyCourseware)
                                    .data("title", dailyCourseware.getBatch().getName() + "-" + dailyCourseware.getName())
                                    .data(CoursewareMovementType.WARM_UP.getAlias(), coursewareService.listCourseware(dailyCourseware, CoursewareMovementType.WARM_UP))
                                    .data(CoursewareMovementType.FORMAL.getAlias(), coursewareService.listCourseware(dailyCourseware, CoursewareMovementType.FORMAL))
                                    .data(CoursewareMovementType.STRETCH.getAlias(), coursewareService.listCourseware(dailyCourseware, CoursewareMovementType.STRETCH));
            }
        } catch (Exception e) {
            logger.error("dailyCourseware() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @param dailyId
     * @param coursewareId
     * @return
     */
    @RequestMapping(value="/coursewares/{coursewareId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult courseware(@RequestParam("unionid") String unionid,
                                 @PathVariable("courseId") Long courseRoundId,
                                 @PathVariable("coursewareId") Long coursewareId) {
        HttpResult httpResult = new HttpResult();
        
        try {
//            User user = userService.load(unionid);
//            Student student = userService.getStudent(user);
            Courseware courseware = coursewareService.loadCourseware(coursewareId);
            
//            if(student == null || courseware == null || courseware.getDaily().getBatch().getCourseRound().getStudent() != student) {
//                httpResult.fail("1").message("课程异常");
//            } else {
                httpResult.success().message("获取数据成功")
                                    .data("courseware", courseware)
                                    .data("movement", courseware.getMovement())
                                    .data("equipment", courseware.getMovement().getEquipment());
//            }
        } catch (Exception e) {
            logger.error("courseware() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    @RequestMapping(value = "/course-coursewares", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult listCourseCourseware(@RequestParam("unionid") String unionid,
                                           @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            if(courseRound.getCourseType().isIndividual()) {
                
                List<CourseSchedule> courseSchedules = courseRoundService.listCourseCourseWare(courseRound);
                
                httpResult.success().message("获取数据成功")
                                    .data("courseType", "INDIVIDUAL")
                                    .data("courseCoursewares", courseSchedules);
            } else {
                BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(courseRound);
                
                httpResult.success().message("获取数据成功")
                                    .data("courseType", courseRound.getCourseType())
                                    .data("courseCoursewares", batchCourseware.getDailyCoursewares());
            }
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("listWeeklyPlan() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    @RequestMapping(value = "/course-coursewares/{dailyCoursewareId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult loadDailyCourseware(@RequestParam("unionid") String unionid,
                                          @PathVariable("courseId") Long courseRoundId,
                                          @PathVariable("dailyCoursewareId") Long dailyCoursewareId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            DailyCourseware dailyCourseware = coursewareService.loadDailyCourseware(dailyCoursewareId);
            
            if(dailyCourseware.getBatch().getCourseRound().getStudent().getId().equals(student.getId())) {
                
                List<CoursewareTag> tags = coursewareService.listCoursewareTags(dailyCourseware.getBatch().getCourseRound().getStudent().getArrayTagIds());
                
                List<Courseware> coursewares = coursewareService.listCourseware(dailyCourseware);
                
                httpResult.success().message("获取数据成功")
                                    .data("dailyCourseware", dailyCourseware)
                                    .data("tags", tags)
                                    .data("coursewares", coursewares);
            } else {
                httpResult.fail("500").message("加载数据失败");
            }
        } catch (Exception e) {
            logger.error("listWeeklyPlan() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
}
